package com.simple.orm.agreement.process.impl;

import com.simple.orm.agreement.annotation.Describe;
import com.simple.orm.agreement.annotation.Protocol;
import com.simple.orm.agreement.process.AbstractWriteProcess;
import com.simple.orm.agreement.utils.DataOutputStreamUtil;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

public class DefaultWriteProcess<T> extends AbstractWriteProcess<T> {

    @Override
    protected void toProtocol(T t, List<Field> list) {
        Class<T> tClass = (Class<T>) t.getClass();
        Protocol protocol = tClass.getDeclaredAnnotation(Protocol.class);
        if (protocol == null)
            throw new IllegalArgumentException(String.format("缺少注解：%s，无法获取协议的唯一标识", Protocol.class.getName()));
        Describe describe = tClass.getDeclaredAnnotation(Describe.class);
        if (describe != null) {
            if (describeEvent != null) describeEvent.event(describe.value());
        }
        try {
            dataOutputStream.writeInt(protocol.value()); // 设置标记位
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 序列化对象
        list.forEach(field -> {
            boolean accessible = field.isAccessible();
            field.setAccessible(true);
            try {
                Object o = field.get(t);
                DataOutputStreamUtil.writeData(dataOutputStream, o);
            } catch (IllegalAccessException | IOException e) {
                throw new RuntimeException(e);
            } finally {
                field.setAccessible(accessible);
            }
        });
        try {
            // 刷新缓冲区
            dataOutputStream.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
